package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传的密码进行md5加密，然后再进行比对
        String md5PassWord = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5PassWord.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        System.out.println("Service  当前线程的ID" + Thread.currentThread().getId());

        // 进行类型转换
        Employee employee = new Employee();

        // 使用Spring提供的工具类 BeanUtils 进行对象属性拷贝-> 前提是这两个类的属性名是一致的
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置账号状态  StatusConstant.ENABLE 启用  StatusConstant.DISABLE 禁用
        employee.setStatus(StatusConstant.ENABLE);

        // 设置默认密码(MD5加密)
        String defaultPassWord = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(defaultPassWord);

        // 创建时间
        //employee.setCreateTime(LocalDateTime.now());

        // 修改时间
        //employee.setUpdateTime(LocalDateTime.now());

        // 设置当前记录创建人和修改人ID
        // 通过ThreadLocal实现id的传递  拦截器 -> Service
        //Long id = BaseContext.getCurrentId();
        //employee.setCreateUser(id);
        //employee.setUpdateUser(id);

        log.info("插入用户数据：{}", employee);

        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1.设置分页参数
        int page = employeePageQueryDTO.getPage();
        int pageSize = employeePageQueryDTO.getPageSize();
        PageHelper.startPage(page, pageSize);

        // 2.执行查询
        List<Employee> employees = employeeMapper.page(employeePageQueryDTO);

        // 3.把原始集合转换为Page集合
        Page<Employee> p = (Page<Employee>) employees;

        // 4.封装pageBean对象
        PageResult pageResult = new PageResult(p.getTotal(), p.getResult());

        return pageResult;
    }

    /**
     * 启用禁用员工账号
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        // 1.传统方式创建对象
//        Employee employee = new Employee();
//        employee.setStatus(status);
//        employee.setId(id);

        // 2.使用构建器的方式创建实体对象
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build(); // 最后调用build方法，构建出对象

        // 传递员工对象，提高方法的通用性
        employeeMapper.update(employee);
    }

    /**
     * 编辑员工
     *
     * @param employeeDTO
     */
    @Override
    public void edit(EmployeeDTO employeeDTO) {
        // 创建员工对象
        Employee employee = new Employee();

        // 员工属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置修改人和修改时间
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

    /**
     * 根据ID查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.SelectById(id);

        // 密码修改成***，提升安全性
        employee.setPassword("***");
        return employee;
    }

}
